#!/usr/bin/env node

// Load required modules
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");

// Parse CLI arguments
const args = process.argv.slice(2);
const packId = args[0];
const bumpType = args[1] || "minor";

// Validate arguments
if (!packId || args.length > 2) {
    console.log(
        "用法: node bump-expansion-version.js <扩展包-id> [major|minor|patch]"
    );
    console.log("默认值: minor");
    console.log(
        "示例: node bump-expansion-version.js sdat-creator-tools patch"
    );
    process.exit(1);
}

if (!["major", "minor", "patch"].includes(bumpType)) {
    console.error("错误: 版本类型必须是 major、minor 或 patch");
    process.exit(1);
}

// Version bump logic
function bumpVersion(currentVersion, type) {
    const [major, minor, patch] = currentVersion.split(".").map(Number);

    switch (type) {
        case "major":
            return `${major + 1}.0.0`;
        case "minor":
            return `${major}.${minor + 1}.0`;
        case "patch":
            return `${major}.${minor}.${patch + 1}`;
        default:
            return currentVersion;
    }
}

// Main function to bump version
async function updateVersion() {
    const configPath = path.join(
        __dirname,
        "..",
        "expansion-packs",
        packId,
        "config.yaml"
    );

    // Check if config exists
    if (!fs.existsSync(configPath)) {
        console.error(`错误: 未找到扩展包 '${packId}'`);
        console.log("\n可用的扩展包:");

        const packsDir = path.join(__dirname, "..", "expansion-packs");
        const entries = fs.readdirSync(packsDir, { withFileTypes: true });

        entries.forEach((entry) => {
            if (entry.isDirectory() && !entry.name.startsWith(".")) {
                console.log(`  - ${entry.name}`);
            }
        });

        process.exit(1);
    }

    try {
        const configContent = fs.readFileSync(configPath, "utf8");
        const config = yaml.load(configContent);

        const oldVersion = config.version || "1.0.0";
        const newVersion = bumpVersion(oldVersion, bumpType);

        config.version = newVersion;

        const updatedYaml = yaml.dump(config, { indent: 2 });
        fs.writeFileSync(configPath, updatedYaml);

        console.log(`✓ ${packId}: ${oldVersion} → ${newVersion}`);
        console.log(`\n✓ 成功更新 ${packId} 的 ${bumpType} 版本`);
        console.log("\n后续步骤:");
        console.log(`1. 测试更改`);
        console.log(
            `2. 提交: git add -A && git commit -m "chore: 升级 ${packId} 版本 (${bumpType})"`
        );
    } catch (error) {
        console.error("更新版本错误:", error.message);
        process.exit(1);
    }
}

updateVersion();
